#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import time
import logging
import traceback
from datetime import datetime
from random import shuffle
from re import sub
from sys import stderr
from traceback import print_exc

# -*- coding: utf-8 -*-
from flask import render_template, url_for, redirect, request, flash, session, abort, Blueprint
from flask_cache import Cache
from werkzeug.utils import secure_filename
from werkzeug.contrib.atom import AtomFeed

from common.form import CommentForm
from models.model import Category, Post, Tag, Comment, pageby, db
from config import PER_PAGE as per_page

# cache = Cache(app, config={'CACHE_TYPE': 'simple'})
# app.config.from_object('config')
# per_page = app.config['PER_PAGE']

category = Blueprint('category', __name__, url_prefix="/category")

log = logging.getLogger(__file__)




class PostFeed(AtomFeed):

    def add_post(self, post):
        self.add(post.post_title,
                 '',
                 content_type="html",
                 author=u'dan',
                 url=post.url,
                 updated=datetime.now(),
                 published=post.post_create_time)


def is_chinese(text):
    if text:
        for uchar in text:
            if uchar >= u'\u4e00' and uchar <= u'\u9fa5':
                return True
    return False


@category.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@category.route('/error/404')
def error_404():
    return render_template('404.html'), 404


@category.route('/category/<int:cateid>')
@category.route('/category/<int:cateid>/page/<int:pageid>')
# @cache.cached(timeout=300)
def category(cateid=1, pageid=1):
    categorys = Category.query.getall()
    hot = Post.query.hottest()[:20]
    new = Post.query.newpost()[:20]
    tag = Tag.query.getall()
    shuffle(tag)
    tag = tag[:20]
    comments = Comment.query.newcomment()[:20]

    cate = Category.query.get_or_404(cateid)

    p = pageby(cate.posts, pageid, per_page, Post.post_create_time.desc())

    articles = p.items
    if not p.total:
        pagination = [0]
    elif p.total % per_page:
        pagination = range(1, p.total / per_page + 2)
    else:
        pagination = range(1, p.total / per_page + 1)

    return render_template('/category.html',
                           id=cateid,
                           cate=cate,
                           categorys=categorys,
                           articles=articles,
                           hotarticles=hot,
                           newpost=new,
                           tags=tag,
                           comments=comments,
                           pageid=pageid,
                           pagination=pagination[pageid - 1:pageid + 10],
                           last_page=pagination[-1]
                           )

@category.route('/error')
def error(content='404'):
    return render_template('/error.html', content=content)
